import dayjs, { type Dayjs } from 'dayjs'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'
import weekday from 'dayjs/plugin/weekday'

// 初始化插件
dayjs.extend(isSameOrBefore)
dayjs.extend(weekday)

// 类型定义
export type DateRange = [Date, Date]
export type DateShortcut = { text: string; value: () => DateRange };

// 1. 快捷选项配置（周一开始）
export const selectShortcuts: DateShortcut[] = [
    createShortcut('前天', () => createSameDayRange(-2)),
    createShortcut('昨天', () => createSameDayRange(-1)),
    createShortcut('今天', () => createSameDayRange(0)),
    createShortcut('上周', () => createWeekRange(-1)),
    createShortcut('本周', () => createWeekRange(0)),
    createShortcut('上月', () => createMonthRange(-1)),
    createShortcut('本月', () => createMonthRange(0))
]

// 2. 禁用未来日期
// export const disableFutureDates = (date: Date) => date > new Date();
export const disableFutureDates = (date: Date) => {
    return dayjs(date).isAfter(dayjs(), 'day'); // 比较日期（忽略时间）
};

// 3. 初始化日期
export const todayDate = () => dayjs().format('YYYY-MM-DD');

// 工具函数封装
function createShortcut(text: string, value: () => DateRange): DateShortcut {
    return { text, value }
}

function createSameDayRange(offset: number): DateRange {
    const date = dayjs().add(offset, 'day')
    return [date.startOf('day').toDate(), date.endOf('day').toDate()]
}

function createWeekRange(offset: number): DateRange {
    const start = dayjs().add(offset, 'week').startOf('week').add(1, 'day')
    const end = dayjs().add(offset, 'week').endOf('week').add(1, 'day')
    return adjustEndDate(start, end)
}

function createMonthRange(offset: number): DateRange {
    const start = dayjs().add(offset, 'month').startOf('month')
    const end = dayjs().add(offset, 'month').endOf('month')
    return adjustEndDate(start, end)
}

function adjustEndDate(start: Dayjs, end: Dayjs): DateRange {
    const today = dayjs()
    return [
        start.toDate(),
        end.isAfter(today) ? today.toDate() : end.toDate()
    ]
}
